package com.ljb.readaloud.v;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.czt.mp3recorder.MP3Recorder;
import com.ljb.readaloud.R;
import com.ljb.readaloud.base.BaseActivity;
import com.ljb.readaloud.cos.COSUtils;
import com.ljb.readaloud.cos.OnCOSUploadListener;
import com.ljb.readaloud.ui.BarWavesView;
import com.ljb.readaloud.utils.AutoUtils;
import com.ljb.readaloud.utils.BitMatrixTool;
import com.ljb.readaloud.utils.QRCode;
import com.ljb.readaloud.utils.T;
import com.ljb.readaloud.utils.ThreadUtils;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends BaseActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String PRE_URL = "https://langduzhe-1253658271.cos.ap-beijing.myqcloud.com/";

    private TextView tvVersion;
    private Chronometer chronometer;
    private BarWavesView bwv1, bwv2;
    private MP3Recorder mp3Recorder;
    private String recordFileDir;
    private String recordFileName;
    private float[] hs;
    private float[] hs_;
    private AlertDialog dialog;
    private Bitmap qrCodeBitmap;

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, MainActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AutoUtils.setSize(this, false, 1439, 803);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        AutoUtils.auto(this);
    }

    @Override
    public void finish() {
        super.finish();
        closeQRcode();
        stop();
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                start();
                break;
            case R.id.stop:
                stop();
                break;
            case R.id.upload:
                upload(v);
                break;
        }
    }

    //开始
    private void start() {
        if (mp3Recorder != null) {
            T.showToast(this, "正在录音中,请先停止录音");
            return;
        }
        startAnim();//动画
        startRecord();//录音
        startTimer();//计时器
    }

    //停止
    private void stop() {
        if (mp3Recorder == null) {
            return;
        }
        stopAnim();//动画
        stopRecord();//录音
        stopTimer();//计时器
    }

    //上传
    private void upload(View view) {
        if (mp3Recorder != null && mp3Recorder.isRecording() || TextUtils.isEmpty(recordFileName) || TextUtils.isEmpty(recordFileDir)) {
            T.showToast(this, "未发现录音文件");
            return;
        }
        view.setClickable(false);
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
                createQRcode();
            }
        });
        cosUpload(view);
    }

    /************************************计时器***********************************************/

    private void startTimer() {
        chronometer.setBase(SystemClock.elapsedRealtime());
        chronometer.start();
    }

    private void stopTimer() {
        chronometer.stop();
    }

    /************************************声波***********************************************/

    private void startAnim() {
        Random random = new Random();
        hs = new float[bwv1.getWaveNumber()];
        hs_ = new float[bwv1.getWaveNumber()];
        for (int i = 0; i < hs.length; i++) {
            float nextFloat = random.nextFloat();
            Log.e(TAG, "run: nextFloat = " + nextFloat);
            hs[i] = nextFloat;
        }
        if (mHandler != null) {
            mHandler.post(mRecordProgressTask);
        }
    }

    private void stopAnim() {
        if (mHandler != null)
            mHandler.removeCallbacksAndMessages(null);
    }

    private static final int UPDATE_TIME = 200;
    private Handler mHandler = new Handler();
    private Runnable mRecordProgressTask = new Runnable() {
        public void run() {
            //录音停止,动画停止
            if (mp3Recorder != null && !mp3Recorder.isRecording()) {
                stop();
            } else {
                updateRecordingUI();
                if (mHandler != null)
                    mHandler.postDelayed(mRecordProgressTask, UPDATE_TIME);
            }
        }
    };

    private void updateRecordingUI() {
        if (mp3Recorder != null) {
            float h = mp3Recorder.getVolume() * 1f / mp3Recorder.getMaxVolume();

            BigDecimal bg = new BigDecimal(h);
            float f = (float) bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();

            Log.e(TAG, "updateRecordingUI: 音量大小比例值=" + f);

            for (int i = 0; i < hs.length; i++) {
                hs_[i] = hs[i] * f;
            }
            bwv1.setWaveHeight(hs_);
            bwv2.setWaveHeight(hs_);
        }
    }

    /******************************录音****************************************************/

    private void startRecord() {
        if (mp3Recorder != null) {
            return;
        }
        File recordFile = new File(recordFileDir = getRecordDirpath(), recordFileName = getRecordName());
        mp3Recorder = new MP3Recorder(recordFile);
        mp3Recorder.setDefaultLameMp3BitRate(96);
        mp3Recorder.setMaxRecordTime(10 * 60 * 1000);
        if (mp3Recorder != null) {
            mp3Recorder.start();
            T.showToast(this, "开始录音成功");
        }
    }

    private void stopRecord() {
        if (mp3Recorder != null) {
            mp3Recorder.stop();
            mp3Recorder = null;
            T.showToast(this, "停止录音成功");
        }
    }

    /**************************************COS************************************************/
    private void cosUpload(final View view) {
        //设置监听
        COSUtils.getInstance().setOnCOSUploadListener(new OnCOSUploadListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                T.showToast(MainActivity.this, "上传成功,扫码下载");
                view.setClickable(true);
            }

            @Override
            public void onError(CosXmlRequest cosXmlRequest, CosXmlClientException clientException, CosXmlServiceException serviceException) {
                T.showToast(MainActivity.this, "上传失败,请重试");
                view.setClickable(true);
            }

            @Override
            public void onProgress(long progress, long max) {
            }
        });
        //上传
        COSUtils.getInstance().upLoad(this, recordFileName, recordFileDir + File.separator + recordFileName);
    }

    /*****************************************二维码*****************************************/

    //生成二维码
    //https://xiaobug-1253658271.cos.ap-beijing.myqcloud.com/20180330_10_40_28.mp3
    private void createQRcode() {
        if (TextUtils.isEmpty(recordFileName)) {
            return;
        }
        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round);
        qrCodeBitmap = BitMatrixTool.init().createLogoQRCodeBitmap(PRE_URL + recordFileName, 500, 500, logo);
//        Bitmap bitmap = QRCode.createQRCodeWithLogo(PRE_URL + recordFileName,logo);

        if (qrCodeBitmap == null) {
            T.showToast(this, "二维码生成失败,请重新上传");
        }

        ThreadUtils.runUIThread(new Runnable() {
            @Override
            public void run() {
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_dialog, null);
                ImageView iv = view.findViewById(R.id.iv_qr);
                iv.setImageBitmap(qrCodeBitmap);

                AutoUtils.auto(view);
                dialog = new AlertDialog.Builder(MainActivity.this)
                        .setView(view)
                        .setCancelable(false)
                        .setTitle("扫描二维码下载")
                        .setPositiveButton("确定", null)
                        .create();

                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }
        });
    }

    private void closeQRcode() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
    }

    /***********************************分隔线***********************************************/

    //获取本地路径
    private String getRecordDirpath() {
        File path = new File(Environment.getExternalStorageDirectory(), "0ReadAloud");
        if (!path.exists() && !path.mkdirs()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            return path.getAbsolutePath();
        }
    }

    //获取文件名称
    private String getRecordName() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault());//设置日期格式
        return "朗读者" + df.format(new Date()) + ".mp3";// new Date()为获取当前系统时间，也可使用当前时间戳
    }

    private void initUI() {
        chronometer = findViewById(R.id.chronometer);
        bwv1 = findViewById(R.id.bwv1);
        bwv2 = findViewById(R.id.bwv2);
        tvVersion = findViewById(R.id.tv_Version);
        tvVersion.setText("v " + getVersion());
    }

    private String getVersion() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    private long firstTime;

    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            firstTime = secondTime;
        } else {
            System.exit(0);
        }
    }
}
